<?php


	namespace app\services;


	use app\lib\exception\ToastException;
	use think\facade\Cache;

	class AccessTokenServices
	{
		const ACCESS_TOKEN = 'access_token_cache';

		//获取token
		public static function getAccessToken () {
			if (Cache::get(self::ACCESS_TOKEN)) {
				return Cache::get(self::ACCESS_TOKEN);
			}

			//重新生成
			return self::accessToken();
		}

		private static function accessToken () {
			$accessTokenUrl = sprintf(config('wx.access_token_url'), config('wx.appid'), config('wx.secret'));
			$ret = json_decode(file_get_contents($accessTokenUrl), true);
			if (array_key_exists('errcode', $ret) && $ret['errcode'] != 0) {
				throw new ToastException($ret['errmsg'], $ret['errcode']);
			}
			Cache::set(self::ACCESS_TOKEN, $ret['access_token'], $ret['expires_in']);

			return $ret['access_token'];
		}

	}
